package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ccp.dev.core.basic.engine.GroovyScriptEngine;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.form.service.impl.ScriptImpl;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.expimp.CustomExcelReader;
import com.ccp.dev.qbdms.expimp.util.AbstractExpUtil;
import com.ccp.dev.qbdms.expimp.util.AbstractImpUtil;
import com.ccp.dev.qbdms.expimp.util.AuxiliaryUtil;
import com.ccp.dev.qbdms.model.WFlightRewardsProject;
import com.ccp.dev.qbdms.model.WQbdQualityRewardsMsgSub;
import com.ccp.dev.qbdms.model.WQbdXhdh;
import com.ccp.dev.qbdms.service.WQbdQualityRewardsMsgSubService;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.StructureModifyUtil;
import com.ccp.dev.system.model.Dictionary;
import com.ccp.dev.core.poi.excel.reader.DataEntity;
import com.ccp.dev.core.poi.excel.reader.ExcelReader;
import com.ccp.dev.core.poi.excel.reader.FieldEntity;
import com.ccp.dev.core.poi.excel.reader.TableEntity;
import java.io.PrintWriter;

import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.service.DictionaryService;
import com.ccp.dev.system.service.SysOrgService;
import com.ccp.dev.system.service.SysUserService;
import net.sf.json.JSONObject;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import com.ccp.dev.qbdms.model.WQbdQualityRewardsMessage;
import com.ccp.dev.qbdms.service.WQbdQualityRewardsMessageService;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.core.basic.annotion.Action;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.ModelMap;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 质量奖惩管理 信息操作处理控制器
 * 
 * @author hw
 * @date 2020-07-06 14:10:36
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "质量奖惩管理")
@RequestMapping("/qbdms/wQbdQualityRewardsMessage")
public class WQbdQualityRewardsMessageController extends SysBaseController{
	@Resource
	private WQbdQualityRewardsMessageService wQbdQualityRewardsMessageService;
    @Resource
    private DictionaryService dictionaryService;
    @Resource
    private WQbdQualityRewardsMsgSubService wQbdQualityRewardsMsgSubService;
    @Resource
    private GroovyScriptEngine engine;
    @Resource
    private SysOrgService sysOrgService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private ScriptImpl scriptImpl;
    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2020-07-06 14:10:36
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description="跳转到质量奖惩管理首页", exectype = "页面跳转日志")
    public String viewList(HttpServletRequest request,ModelMap modelMap) {
        // 类别
        List<Dictionary> lbList = dictionaryService.getDicByNodeKey("lb", false);
        modelMap.put("lbList", JSON.toJSONString(lbList));
        modelMap.put("currentUserId", scriptImpl.getCurrentUserId());
        return "wQbdQualityRewardsMessage/list";
    }

    /**
    * 功能描述: 附带检索条件的分页查询
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: hw
    * @date: 2020-07-06 14:10:36
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description="附带检索条件的分页查询质量奖惩管理",detail="查询数据信息<#if success>成功<#else></#if>")
    public Object list(HttpServletRequest request) {
        QueryFilter queryFilter = new QueryFilter(request, true);

        ZhiLiangConst.addQueryFilter(queryFilter);
        //分页数据
        List<WQbdQualityRewardsMessage> pageDatas = wQbdQualityRewardsMessageService.queryList(queryFilter);
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2020-07-06 14:10:36
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description="跳转到质量奖惩管理新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        // 类别
        List<Dictionary> lbList = dictionaryService.getDicByNodeKey("lb", false);
        modelMap.put("lbList", JSON.toJSONString(lbList));
        //是否行政处分
        List<Dictionary> sfList = dictionaryService.getDicByNodeKey("sf", false);
        modelMap.put("sfList",JSON.toJSONString(sfList));

        if (StringUtil.isEmpty(id)) {
            // 新增
            // 填报信息
            modelMap.put("filldept", engine.executeObject("return scriptImpl.getCurrentOrgName();", null).toString());
            modelMap.put("fillman", engine.executeObject("return scriptImpl.getCurrentName();", null).toString());
            modelMap.put("filldate", engine.executeObject("return scriptImpl.getCurrentDate();", null).toString());
        } else {
            try {
                // 编辑
                WQbdQualityRewardsMessage wFlightRewardsProject = wQbdQualityRewardsMessageService.getOneById(id);
                // 填报信息
                modelMap.put("filldept", wFlightRewardsProject.getFilldept());
                modelMap.put("fillman", wFlightRewardsProject.getFillman());
                modelMap.put("filldate", wFlightRewardsProject.getFilldate());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return "wQbdQualityRewardsMessage/add";
    }

    /**
    * 功能描述:  数据保存通用方法
    *
    * @param: wQbdQualityRewardsMessage 保存的对象
    * @return: java.lang.Object
    * @auther: hw
    * @date: 2020-07-06 14:10:36
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description="保存质量奖惩管理数据",detail="<#if isAdd>新增<#else>编辑</#if>质量奖惩管理数据<#if success>成功<#else>失败</#if>")
    public Object save(@RequestBody WQbdQualityRewardsMessage wQbdQualityRewardsMessage) {
        String id = wQbdQualityRewardsMessage.getId();
        //设置来源为其他
        wQbdQualityRewardsMessage.setDataFrom(ZhiLiangConst.RESTS);
        int result;
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("isAdd",true);
            //新增操作
            //新增数据前生成随机Id
            wQbdQualityRewardsMessage.setId(UUIDUtils.getUUIDFor32());
            //公共字段的赋值
            ZhiLiangConst.addCommonFields(wQbdQualityRewardsMessage);
            result = wQbdQualityRewardsMessageService.add(wQbdQualityRewardsMessage);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            WQbdQualityRewardsMessage oldWQbdQualityRewardsMessage = wQbdQualityRewardsMessageService.getOneById(id);
            String modifyInfo = StructureModifyUtil.getModifyInfo(oldWQbdQualityRewardsMessage, wQbdQualityRewardsMessage);
            SysAuditThreadLocalHolder.putParamerter("modifyInfo",modifyInfo);
            ZhiLiangConst.updateCommonFields(wQbdQualityRewardsMessage);
            //修改操作
            result = wQbdQualityRewardsMessageService.update(wQbdQualityRewardsMessage);
        }
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
    }

    /**
    * 功能描述: 跳转到详情页面
    *
    * @return: java.lang.String
    * @auther: hw
    * @date: 2020-07-06 14:10:36
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description="跳转到质量奖惩管理详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        // 类别
        List<Dictionary> lbList = dictionaryService.getDicByNodeKey("lb", false);
        modelMap.put("lbList", JSON.toJSONString(lbList));
        //是否行政处分
        List<Dictionary> sfList = dictionaryService.getDicByNodeKey("sf", false);
        modelMap.put("sfList",JSON.toJSONString(sfList));

        // 编辑
        WQbdQualityRewardsMessage wFlightRewardsProject = wQbdQualityRewardsMessageService.getOneById(id);
        // 填报信息
        modelMap.put("filldept", wFlightRewardsProject.getFilldept());
        modelMap.put("fillman", wFlightRewardsProject.getFillman());
        modelMap.put("filldate", wFlightRewardsProject.getFilldate());
        return "wQbdQualityRewardsMessage/particulars";
    }

    /**
    * 功能描述: 根据主键id获取一条数据的通用查询方法
    *
    * @param: id 参数对象必须是"id"
    * @return: java.lang.Object
    * @auther: hw
    * @date: 2020-07-06 14:10:36
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description="根据主键id查询质量奖惩管理的一条数据",detail="根据主键id查询质量奖惩管理的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String id) {
        WQbdQualityRewardsMessage wQbdQualityRewardsMessage = wQbdQualityRewardsMessageService.getOneById(id);

        List<WQbdQualityRewardsMsgSub> wQbdQualityRewardsMsgSubList = wQbdQualityRewardsMsgSubService.getListByRefId(id);

        wQbdQualityRewardsMessage.setwQbdQualityRewardsMsgSubList(wQbdQualityRewardsMsgSubList);

        if (null == wQbdQualityRewardsMessage) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("get.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return getResultDataSuccess("get.success",wQbdQualityRewardsMessage);
    }

    /**
    * 功能描述: 根据主键ID删除数据的通用删除方法
    *
    * @param: id 参数名称必须是"id"
    * @return: java.lang.Object
    * @auther: hw
    * @date: 2020-07-06 14:10:36
    */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description="根据主键ID删除质量奖惩管理数据",exectype = "删除日志",detail="删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String id) {
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return fail("delete.failure.message");
        }
        String[] ids = id.split(",");
        for(int i=0;i<ids.length;i++){
            WQbdQualityRewardsMessage wQbdQualityRewardsMessage = wQbdQualityRewardsMessageService.getOneById(ids[i]);
            if(!(ZhiLiangConst.RESTS.equals(wQbdQualityRewardsMessage.getDataFrom()))){
                return fail("来源为质量问题与飞行试验的数据不允许删除!");
            }
            if(!(ContextUtil.getCurrentUserId().equals(wQbdQualityRewardsMessage.getCreateBy()))){
                return fail("删除失败，只能删除自己创建的数据!");
            }
        }
        int result = wQbdQualityRewardsMessageService.delByIdArray(id.split(","));
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }

    /**
    * 功能描述: 跳转到导入页面
    *
    * @return: java.lang.String
    * @auther: hw
    * @date: 2019-12-25 19:21:40
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    @Action(description="跳转到质量奖惩管理导入页面", exectype = "页面跳转日志")
    public String viewImport() {
        return "wQbdQualityRewardsMessage/import";
    }

    /**
     * 功能描述: 跳转到导出选择字段页面
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2019-12-25 19:21:40
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/export")
    @Action(description="跳转到质量问题导出选择字段页面", exectype = "页面跳转日志")
    public String export(HttpServletRequest request,ModelMap modelMap) throws Exception {
        com.alibaba.fastjson.JSONObject jsonObject = AuxiliaryUtil.resolverModel(WQbdQualityRewardsMessage.class);
        modelMap.put("tableInfo",jsonObject.toString());
        return "expImp/add";
    }

    /**
    * 功能描述: 导出质量奖惩管理数据信息
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: hw
    * @date: 2020-07-06 14:10:36
    */
    @RequestMapping("/exportData")
    @Action(description="导出质量奖惩管理数据信息",detail="导出质量奖惩管理数据信息<#if success>成功<#else></#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception{
        SysAuditThreadLocalHolder.putParamerter("success",false);
        String[] id = RequestUtil.getStringAryByStr(request,"id");
        QueryFilter queryFilter = new QueryFilter(request,false);
        JSONArray dataArray = ZhiLiangConst.exportAddConditions(queryFilter,id);
        queryFilter.addFilter("belongdeptname", BaseUtil.getCurrentTenOrgCodePath() + "%");
        List<WQbdQualityRewardsMessage> wQbdQualityRewardsMessages = this.wQbdQualityRewardsMessageService.queryAll(queryFilter);
        if(wQbdQualityRewardsMessages.isEmpty()){
            wQbdQualityRewardsMessages.add(new WQbdQualityRewardsMessage());
        }

        new AbstractExpUtil() {
            @Override
            public String customAnalysis(String fieldName, String fieldValue) {
                return null;
            }
        }.executeExport(request,response,wQbdQualityRewardsMessages,dataArray,"质量奖惩信息", AbstractExpUtil.ExpStyle.MANY_SHEET);

        SysAuditThreadLocalHolder.putParamerter("success",true);
    }

    /**
    * 导入资源文件
    * @param request
    * @param response
    * @throws Exception
    */
    @RequestMapping("/importData")
    @ResponseBody
    public ResultData importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception{
        SysAuditThreadLocalHolder.putParamerter("success",false);
        MultipartFile multipartFile = request.getFile("file");
        TableEntity excelEntity = new CustomExcelReader().readFile(multipartFile.getInputStream());
        Map<String, Object> map = new AbstractImpUtil() {
            @Override
            public ReturnType customValidation(String fieldName, String fieldValue) {
                ReturnType returnType = null;
                //特殊字段自定义验证
                if("headcount".equals(fieldName)){
                    returnType = new AbstractImpUtil.ReturnType();
                    boolean sign = true;
                    try {
//                        Integer.parseInt(fieldValue);
                        Long.parseLong(fieldValue.replace(",",""));
                        returnType.setNewValue(fieldValue.replace(",",""));
                        sign = false;
                    } catch (Throwable t) {
                    }
                    if (sign) {
                        returnType.setMsg("非法的值!");
                    }
                }
                if("disciplinarySanctionCount".equals(fieldName)){
                    returnType = new AbstractImpUtil.ReturnType();
                    boolean sign = true;
                    try {
//                        Integer.parseInt(fieldValue);
                        Long.parseLong(fieldValue.replace(",",""));
                        returnType.setNewValue(fieldValue.replace(",",""));
                        sign = false;
                    } catch (Throwable t) {
                    }
                    if (sign) {
                        returnType.setMsg("非法的值!");
                    }
                }
                if("money".equals(fieldName)){
                    returnType = new AbstractImpUtil.ReturnType();
                    boolean sign = true;
                    try {
                        new BigDecimal(fieldValue.replace(",",""));
                        returnType.setNewValue(fieldValue.replace(",",""));
                        sign = false;
                    } catch (Throwable t) {
                    }
                    if (sign) {
                        returnType.setMsg("非法的值!");
                    }
                }
                return returnType;
//                ReturnType returnType = null;
//                return returnType;
            }
        }.reverseModels(excelEntity, WQbdQualityRewardsMessage.class);
        String msg = map.get("msg").toString();
        List<WQbdQualityRewardsMessage> list = (List<WQbdQualityRewardsMessage>)map.get("instList");
        if(StringUtil.isEmpty(msg)){
            this.wQbdQualityRewardsMessageService.addImportData(list);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("dataSource.importXml.success");
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return fail(msg);
        }
    }


}
